package com.lagou;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

@Configuration
public class SpringConfig {
    /**
     * 连接工厂
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        return new CachingConnectionFactory(URI.create("amqp://guest:guest@localhost:5672/%2f"));
    }

    /**
     * RabbitTemplate：消息发送接收的主类
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }

    /**
     * 自动声明交换器，队列及绑定
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * 定义交换器
     */
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("MyDirectExchange", true, true, null);
    }

    /**
     * 定义队列
     */
    @Bean
    public Queue queue() {
        return new Queue("MyQueue", true, false, true, null);
    }

    /**
     * 定义绑定
     */
    @Bean
    public Binding binding() {
        return new Binding("MyQueue", Binding.DestinationType.QUEUE, "MyDirectExchange", "MyBindingKey", null);
    }
}
